<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">

<!-- Imports used in this page -->
<link rel="import" href="components/app-container.html">
<link rel="import" href="components/app-navigation.html">

<dom-module id="main-view">
  <template>
    <style>
      app-container {
        background-color: var(--lumo-shade-5pct);
        color: var(--lumo-body-text-color);
        font-family: var(--lumo-font-family);
        overflow: auto;
        flex-direction: column;
      }

      @media (max-width: 600px) {
        app-navigation {
          transition: all 0.5s;
          height: 52px;
        }

        app-navigation[nav-hidden] {
          height: 0;
        }

        app-container {
          flex-direction: column-reverse;
        }
      }

      .offline[hidden] {
        display: none !important;
      }
    </style>

    <iron-ajax auto url="offline-page.html" handle-as="document" last-response="{{offlinePage}}"></iron-ajax>

    <app-container id="appContainer">
      <app-navigation id="appNavigation" nav-hidden$="[[navHidden]]"></app-navigation>
      <slot></slot>
    </app-container>

    <div id="offline" class="offline" hidden$="[[online]]">
    </div>
  </template>

  <script>
    class MainView extends Polymer.Element {
      static get is() {
        return 'main-view';
      }

      static get observers() {
        return ['_offlinePageChanged(offlinePage)'];
      }

      // Reusing offline-page.html content in order not to duplicate.
      // The page is requested using iron-ajax.
      _offlinePageChanged(doc) {
        if (doc) {
          this.$.offline.appendChild(doc.querySelector('style'));
          this.$.offline.appendChild(doc.querySelector('.content'));
        }
      }

      ready() {
        super.ready();

        // This might be provided by flow in the future (#3778)
        this.online = window.navigator.onLine;
        window.addEventListener('online', e => this.online = true);
        window.addEventListener('offline', e => this.online = false);

        // In small devices we hide nav-bar when soft-keyboard is displayed.
        try {
          // It's a touch device
          document.createEvent('TouchEvent');
          // Hide the bar when height is small enough (a timeout is needed in iOS)
          const hideNav = () => setTimeout(() => this.navHidden = this.focused && window.innerHeight <= 600);
          // search-bar notifies when input field is focused
          this.addEventListener('search-focus', e => (this.focused = true, hideNav()));
          this.addEventListener('search-blur', e => (this.focused = false, hideNav()));
          window.addEventListener('resize', e => hideNav());
        } catch (e) {
          // NOP: not a touch device
        }
      }
    }

    window.customElements.define(MainView.is, MainView);
  </script>
</dom-module>
